package com.lincoln.framework.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * FreeMarker 辅助类
 * @author Rubekid
 *
 */
public class FreeMarkerUtils{
	
	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(FrameworkLogger.class);
	
	/**
	 * 模板路径
	 */
	public final static String TEMPLATE_PATH = "/files/ftl/";
	
	private static Properties properties;
	
	
	static{
		initProperties();
	}
	
	/**
	 * 获取模板内容
	 * @param tpl
	 * @param rootMap
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String fetch(String tpl, Object rootMap) throws IOException, TemplateException{
		Template template = getTemplate(tpl);
		Writer out= new StringWriter();
		template.process(rootMap, out);
		String result = out.toString();
		out.flush();
		return result;
	}
	
	/**
	 * 输出显示
	 * @param tpl
	 * @param rootMap
	 * @param out
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static void display(String  tpl, Object rootMap, Writer out) throws IOException, TemplateException{
		Template template = getTemplate(tpl);
		template.process(rootMap, out);
		out.flush();
	}
	
	/**
	 * 获取模板
	 * @param tpl
	 * @param dir
	 * @return
	 * @throws IOException
	 * @throws TemplateException 
	 */
	private static Template getTemplate(String tpl) throws IOException, TemplateException{
		Configuration config = new Configuration();
        config.setSettings(properties);
		String path = StringUtilsEx.getContextPath() + TEMPLATE_PATH;
		String name =  tpl;
		int pos = tpl.lastIndexOf("/");
		if(pos > -1){
			path += tpl.substring( 0, pos+1 );
			name = tpl.substring( pos+1 );
		}
		
		config.setDirectoryForTemplateLoading(new File(path));
		config.setObjectWrapper(new DefaultObjectWrapper());

		return  config.getTemplate(name ,"utf-8");
	}
	
	private static void initProperties(){
		try{
			properties = new Properties();
		}
		catch(Exception ex){
			logger.error(ex.getMessage(), ex);
		}
	}
	
	/**
	 * 获取模板（通过字符串）
	 * @param source
	 * @throws IOException 
	 */
	@SuppressWarnings("unused")
	private static Template getTemplateBySource(String name, String source) throws IOException{
		Configuration config = new Configuration();
		StringTemplateLoader loader = new StringTemplateLoader();
		loader.putTemplate(name, source);
		config.setTemplateLoader(loader);
		return config.getTemplate(name, "utf-8");
	}
}
